package com.alinesno.cloud.common.core.datasource;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * <p>
 * 多数据源的配置,并支持多从库
 * </p>
 *
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
	
    @SuppressWarnings("unused")
	private static final Logger log = LoggerFactory.getLogger(DynamicDataSource.class);

    private static final AtomicLong dbCount = new AtomicLong(0L);
    private static final ThreadLocal<String> dataSourceHolder = new ThreadLocal<String>();

    /**
     * 选择使用数据库，并把选择放到当前ThreadLocal的栈顶
     */
    public static void use(String key, int dbSize) {
        if (dbSize < 1) {
            dataSourceHolder.set(key);
        } else {
            long c = dbCount.incrementAndGet();
            c = c % dbSize;
            dataSourceHolder.set(key + c);
        }
    }

    /**
     * 重置
     */
    public static void reset() {
        dataSourceHolder.remove();
    }

    /**
     * 如果是选择使用数据库
     */
    @Override
    protected Object determineCurrentLookupKey() {
        String key = dataSourceHolder.get();
        return key;
    }

}